package hasWeight;

import DFS.Graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 求取有权图的联通分量
 */
public class CCollection {
    private WeightedGraph graph;
    private int[] visited;
    private int ccount = 0;

    public CCollection(WeightedGraph graph) {
        this.graph = graph;
        this.visited = new int[graph.getVertexNum()];
        for (int i = 0; i < this.visited.length; i++) {
            this.visited[i] = -1;
        }
        for (int v = 0; v < graph.getVertexNum(); v++) {
            if (this.visited[v] == -1) {
                dfs(v, this.ccount);
                this.ccount++;
            }
        }
    }

    private void dfs(int v, int colNum) {
        this.visited[v] = colNum;
        for (int w : graph.adj(v)) {
            if (this.visited[w] == -1) {
                dfs(w, colNum);
            }
        }
    }

    public boolean isCollected(int v, int w) {
        this.graph.validateVertex(v);
        this.graph.validateVertex(w);
        return visited[v] == visited[w];
    }

    public int count() {
        return this.ccount;
    }

    public List<Integer>[] components() {
        List<Integer>[] res = new ArrayList[this.ccount];
        for (int i = 0; i < this.ccount; i++) {
            res[i] = new ArrayList<>();
        }
        for (int v = 0; v < this.graph.getVertexNum(); v++) {
            res[visited[v]].add(v);
        }
        return res;
    }

    public int[] getVisited() {
        return this.visited;
    }

    public static void main(String[] args) {
        WeightedGraph graph = new WeightedGraph("weightedGraph.txt");
        CCollection cc = new CCollection(graph);
        System.out.println(cc.count());
        System.out.println(Arrays.toString(cc.getVisited()));
        List<Integer>[] com = cc.components();
        for (int i = 0; i < com.length; i++) {
            System.out.print(i + " : ");
            System.out.println(com[i]);
        }
    }
}
